//	--------------------------------------------------------------------
//	Copyright(C) 2006,2007 Zhao Yukun. All rights reserved.
//	This file is a part of the Xeres system.
//	Xeres 2007
//	Contact : xeres.engine@gmail.com
//	$(reservedInfo)
//	$(reservedDeclaration)
//	--------------------------------------------------------------------
///	@file	<CBaseIndex9.cpp>
///	@path	~/src/graphics/dx9/
///	@date	2009/01/13
///	@desc	.

#include "config/config.h"

#include "graphics/dx9/CBaseIndex9.h"

namespace xeres {

	IMPL_IOBJECT_CLASS( CBaseIndex9 );
	
	// CBaseIndex9
	CBaseIndex9::CBaseIndex9( IDirect3DIndexBuffer9 * buffer , size_t count )
		: m_pBuffer( buffer )
		, m_count( count )
	{
		HRESULT hr = m_pBuffer->GetDesc( &m_desc );
		XS_ASSERT( SUCCEEDED(hr) );
	}
	// ~CBaseIndex9
	CBaseIndex9::~CBaseIndex9( void )
	{
		if( m_pBuffer )
		{
			UINT rest = m_pBuffer->Release();
			if( rest != 0 )
			{
				TRACE_ERROR( _S("CBaseIndex9::DTOR: Invalid IDirect3DIndexBuffer9 reference count.") );
				FATAL_ABORT( _S("Invalid IDirect3DIndexBuffer9 reference count.") );
			}
		}
	}
	// OnLostDevice
	bool CBaseIndex9::OnLostDevice( void )
	{
		return true;
	}
	// OnResetDevice
	bool CBaseIndex9::OnResetDevice( RefWeak<IDevice> device )
	{
		return true;
	}
	// GetCount
	size_t CBaseIndex9::GetCount( void )
	{
		return m_count;
	}
	// GetSize
	size_t CBaseIndex9::GetSize( void )
	{
		return m_desc.Size;
	}
	// IsWritable
	bool CBaseIndex9::IsWritable( void )
	{
		return !(m_desc.Pool & D3DPOOL_DEFAULT);
	}
	// IsReadable
	bool CBaseIndex9::IsReadable( void )
	{
		return !(m_desc.Pool & D3DPOOL_DEFAULT) && ( m_desc.Usage & D3DUSAGE_DYNAMIC );
	}
	// Map
	bool CBaseIndex9::Map( bool discard , ResourceMap& data )
	{
		TRACE_ERROR( _S("CBaseIndex9::Map: Not implemented.") );
		FATAL_ABORT( _S("Not implemented call.") );
		return false;
	}
	// ReadBack
	bool CBaseIndex9::ReadBack( ResourceMap& data , bool readonly )
	{
		TRACE_ERROR( _S("CBaseIndex9::ReadBack: Not implemented.") );
		FATAL_ABORT( _S("Not implemented call.") );
		return false;
	}
	// Unmap
	bool CBaseIndex9::Unmap( void )
	{
		TRACE_ERROR( _S("CBaseIndex9::Unmap: Not implemented.") );
		FATAL_ABORT( _S("Not implemented call.") );
		return false;
	}
	// GetVertexInterface
	IUnknown * CBaseIndex9::GetVertexInterface( void )
	{
		return NULL;
	}
	// GetIndexInterface
	IUnknown * CBaseIndex9::GetIndexInterface( void )
	{
		return m_pBuffer;
	}
	// GetFormat
	DXFormat CBaseIndex9::GetFormat( void )
	{
		return DXFormat( m_desc.Format );
	}
	// ApplyIndex
	void CBaseIndex9::ApplyIndex( RenderContext& rc )
	{
		HRESULT hr = rc.GetDX9()->SetIndices( m_pBuffer );
		if( FAILED(hr) )
		{
			TRACE_ERROR( _S("CBaseIndex9::ApplyIndex: Failed to set index: %s") , d3d_get_err(hr) );
		}
	}

} // namespace xeres
